class Cart{
     constructor(){
          //获取购物车信息，渲染页面
          this.init()
     }
     async init(){
        if(!cookie){
            location.href='http://localhost:4023/html/login.html'
        }
         //获取数据
        //  console.log(this);
         let data=await this.getData()
        //  console.log(data.carts)
        //  console.log("data:",data[0].carts);
         let datas=data.carts
         this.create(datas) //渲染页面
         this.addsub(data) // 购买数量变化
         this.select(data) // 选择
         this.total() //总计
         this.delet()//删除按钮
     }
     async getData(){
         let data=await axios.get(`http://localhost:1998/userinfo/${cookie}`)
         return data.data
     }
     //渲染数据
     create(data){
        let tbody=document.querySelector(".mycart_list tbody")
        // console.log(data)
        let str=''
        data.map(item=>{
            str += `
             <tr prodId=${item.id}>
            <td>
                <span class="check ${item.checked  ? 'active' : ''}"></span>
            </td>
            <td><img src="${item.img.showimg}" alt=""></td>
            <td>${item.name}</td>
            <td class="td1">1套
            </td>
            <td>￥${item.price}</td>
            <td>
                <div class="tb_jian">
                    <span href=""></span>
                </div>
                <div class="tb_count">
                    <input type="text" value="${item.num}">
                </div>
                <div class="tb_jia">
                    <span href=""></span>
                </div>
            </td>
            <td>￥<b class="xj">${(item.price * item.num).toFixed(2)}</b>
            </td>
            <td class='del'>删除</td>
        </tr>`
       })

        tbody.innerHTML=str
    }
   
    //加减按钮
    addsub(data){
        // console.log(this);
        let jias=document.querySelectorAll(".tb_jia"),
            jians=document.querySelectorAll(".tb_jian")
            // inputs=document.querySelectorAll(".tb_count")
        // console.log(this);
        for(let i=0;i<jias.length;i++){
            jias[i].onclick=()=>{
               
                this.changenum("jia",jias[i],i,data)
            }
            jians[i].onclick=()=>{
                // console.log(this);
               this.changenum("jian",jians[i],i,data)
            }
        }
    }
    async changenum(str,btn,i,data){
        // console.log(data);
        let id=btn.parentNode.parentNode.getAttribute('prodid')
        // console.log(i);
        if(str==="jia"){
            data.carts[i].num++
        }
        else if(str==="jian"){
            if(data.carts[i].num>1){
                data.carts[i].num--
            }
        }
        // console.log(that);
        // let res=axios.get(`http://localhost:1998/carts?phone=987654`,data[i])
        // console.log(data);
       let res=await axios.put(`http://localhost:1998/userinfo/${cookie}`,data)
    //    console.log(res);
       this.init(data)
    }

    //选择
    select(data){
        let checks=document.querySelectorAll('.check')
        //先控制全选按钮
        this.changeAll(checks)
        // console.log(data);
        for(let i=0;i<checks.length;i++){
            checks[i].onclick=()=>{
            //获取按钮的类名 
             let classname = checks[i].getAttribute('class')
              //点击非全选按钮
              if(!classname.includes('checkAll')){
                classname.includes('active')?data.carts[i-1].checked=false:data.carts[i-1].checked=true
                axios.put(`http://localhost:1998/userinfo/${cookie}`,data)
                this.init()
              }else{
                  //点击全选按钮
                  this.selectAll(checks[i],checks,data)
              }
              
            }
        }
    }
    //非全选对全选按钮的控制
    changeAll(checks){
        let arr = Array.from(checks)  //伪数组转化为真数组
        
        //遍历所有非全
        let res=arr.splice(1).every(item=>{
            return item.getAttribute('class').includes('active')
        })
        if(res){
            arr[0].classList.add('active')
        }else{
            arr[0].classList.remove('active')
        }

    }
    //全选
    selectAll(check,checks,data){
        //首先判断全选按钮样式
        let hasactive=check.getAttribute('class').includes('active')
        for(let i=0;i<checks.length-1;i++){
            data.carts[i].checked=!hasactive  //商品选择全部取反
        }
        axios.put(`http://localhost:1998/userinfo/${cookie}`,data)
       
        //全选按钮样式改变
        if(!!hasactive){
            check.classList.remove('active')
        }else{
            check.classList.add('active')
        }
        this.init()
    }

    // 总计
    async total(){
        
        let data=await this.getData()
        // console.log(data.carts);
        //购物车总计
        let cartnum=document.querySelector(".top_shop em")
        // console.log(cartnum);
        //所有li中的input
        let ipts=document.querySelectorAll('.tb_count input')
        //总数
        let num=0
        Array.from(ipts).map(item=>{
             num+=item.value-0
        })
       cartnum.innerText=num
        let allnum=document.querySelector("#sum_count")
        let allprice=document.querySelector("#sum_price")
        //选中数量  获取
        let totalnum=0,totalprice=0
        data.carts.map(item=>{
             item.checked?totalnum+=item.num-0:totalnum
             item.checked?totalprice+=(item.price-0)*(item.num-0):totalprice
        })
        // console.log(totalnum,totalprice);
        allnum.innerText=totalnum
        allprice.innerText=totalprice

    }

    //删除
    async delet(){
        let data=await this.getData()
        ,cart=data.carts
        ,dels=document.querySelectorAll(".del")
        // console.log(cart);
        Array.from(dels).map((item,index)=>{
            item.onclick=async ()=>{
                // console.log(item,index);
                cart.splice(index,1)
                // console.log('cart',cart);
                data.carts=cart
                await axios.put(`http://localhost:1998/userinfo/${cookie}`,data)
                this.init()
            }
        })
    }

    
}

new Cart()